<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 验证码控制器
 * @property ApiOutput $apiOutput
 */
class Captcha extends CI_Controller {

	public function __construct(){
		parent::__construct();
	}
	/**
	 * 发送验证码
	 * 传入参数:手机号码
	 */
	public function send(){

		$input = check_input($_REQUEST,array('phone','rqst','token'));
		if( empty($input) ){
			$this->apiOutput->error('参数错误',$this->apiOutput->eParam);
		}
		if( empty($input['phone']) ){
			$this->apiOutput->error('请输入正确的手机号码',-1);
		}
		if( !is_numeric($input['rqst']) ){
			$this->apiOutput->error('参数错误',$this->apiOutput->eParam);
		}

		$phone       = $input['phone'];
		$requestTime = $input['rqst'];
		$token       = $input['token'];
		if( ! $this->checkToken($requestTime, $phone, $token) ){
			$this->apiOutput->error('系统繁忙,请稍后再试[2]',-2);
		}

		$this->load->library('PhoneCaptcha');
		$res = PhoneCaptcha::send($phone);//发送验证码

		if( 0==$res['error'] ){
			$this->apiOutput->put('msg', '短信发送成功!')->out();
		}else{
			$this->apiOutput->error($res['msg'],-3);
		}
	}
	/**
	 * 验证令牌
	 * @return boolean
	 */
	private function checkToken($time,$phone,$token){
		if( defined('IS_TEST') && IS_TEST  ){
			return true;
		}
		$num = $time - $phone*55;
		$num = round( abs(sin($num)) , 6 )+0.141592;
		$check = md5($num);
		return strcasecmp($token, $check)===0 ? TRUE : FALSE;
	}
	
	public function check(){
		$input = check_input($_REQUEST,array('phone','captcha'));
		if( empty($input) ){
			$this->apiOutput->error('参数错误',$this->apiOutput->eParam);
		}
		if( empty($input['phone']) ){
			$this->apiOutput->error('请输入正确的手机号码',-1);
		}
	}
}